﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml.Linq;
using KMF.Common;
using KMF.DAL;
using KMF.Utility;
using KMF.WebUI.Models;
using ImageResizer;
using KMF.WebUI.Infrastructure;

namespace KMF.WebUI.Areas.KMFadmin.CustomHelpers
{
    public class FunctionHelper
    {
        public static List<object> GoldenTimeStatus()
        {
            return new List<object>     {
                                            new  { ItemValue = "kichhoat", ItemText = "Kích hoạt"},
                                            new  { ItemValue = "chuakichhoat", ItemText = "Chưa kích hoạt"}
                                        };
        }


        public static List<NewsCategoryDto> GetMenuListThreeLevelNews()
        {
            var result = new List<NewsCategoryDto>();
            var menuList = NewsCategoryDb.GetAll() ?? new List<NewsCategoryDto>();
            var topMenuList = (from m in menuList where m.ParentId == 0 select m).OrderBy(m => m.Ordering);
            foreach (var item in topMenuList)
            {
                result.Add(item);
                var subMenuList = (menuList.Where(m => m.ParentId == item.Id).OrderBy(m => m.Ordering));
                foreach (var subItem in subMenuList)
                {
                    subItem.CateName = "----" + subItem.CateName;
                    result.Add(subItem);
                    var childMenuList = (from m in menuList where m.ParentId == subItem.Id select m).OrderBy(m => m.Ordering);
                    foreach (var childItem in childMenuList)
                    {
                        childItem.CateName = "----------" + childItem.CateName;
                        result.Add(childItem);
                    }
                }
            }
            result.Insert(0, new NewsCategoryDto { Id = 0, CateName = "-- Nhóm tin --" });
            return result;
        }
           
        public static string UploadImages(out string error, string fullFolder, HttpPostedFileBase fileUpload)
        {
            var isValid = true;
            var fileName = string.Empty;
            var filePathSaved = string.Empty;
            var e = "";
            //var url = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["CategoryImagesPath"]);
            var name = fileUpload.FileName;
            if (string.Compare(fileUpload.ContentType, "image/png", true) != 0 &&
                string.Compare(fileUpload.ContentType, "image/jpeg", true) != 0 &&
                string.Compare(fileUpload.ContentType, "image/gif", true) != 0)
            {
                e = "Bạn phải sử dụng file ảnh có định dạng jpg, png, gif.";
                isValid = false;
            }
            if (isValid)
            {
                try
                {
                    var extension = Path.GetExtension(fileUpload.FileName) ?? "";
                    fileName = Path.GetFileName(string.Format("{0}-{1}.{2}", StringUtil.RemoveSpecialCharactersVn(name.Replace(extension, "")).GetNormalizeString(), GenerateId(), "jpg"));
                    if (!Directory.Exists(fullFolder)) Directory.CreateDirectory(fullFolder);
                    fileUpload.SaveAs(Path.Combine(fullFolder, fileName ?? ""));
                    filePathSaved = fileName;
                }
                catch (Exception ex)
                {
                    e = ex.Message;
                }
            }
            error = e;
            return filePathSaved;
        }

        public static string UploadDocument(string name, string url, out string error, string oldFileName, HttpPostedFileBase fileUpload)
        {
            var isValid = false;
            var fileName = string.Empty;
            string e = "";
            string a = fileUpload.ContentType;
            if (fileUpload != null)
            {
                isValid = true;
                if (string.Compare(fileUpload.ContentType, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", true) != 0 &&
                    string.Compare(fileUpload.ContentType, "application/msword", true) != 0 &&
                    string.Compare(fileUpload.ContentType, "application/pdf", true) != 0 &&
                    string.Compare(fileUpload.ContentType, "application/x-pdf", true) != 0)
                {
                    e = "Bạn phải sử dụng file ảnh có định dạng jpg, png, gif.";
                    isValid = false;
                }
                if (isValid)
                {
                    var extension = Path.GetExtension(fileUpload.FileName);
                    fileName = Path.GetFileName(string.Format("{0}-{1}{2}", StringUtil.RemoveSpecialCharactersVn(name.GetNormalizeString()),
                                                       (new Random()).Next(9999), extension));
                    fileUpload.SaveAs(url + fileName);
                    var odlPicturePath = string.Format("{0}{1}", url, oldFileName);
                    if (System.IO.File.Exists(odlPicturePath))
                    {
                        System.IO.File.Delete(odlPicturePath);
                    }

                }
            }
            error = e;
            return fileName;
        }

        public static string EnCryptData(string strSource)
        {
            var md5Hasher = new MD5CryptoServiceProvider();
            byte[] btys = null;
            var strDes = string.Empty;
            var encoder = new UTF8Encoding();
            btys = md5Hasher.ComputeHash(encoder.GetBytes(strSource));
            for (int i = 0; i <= btys.Length - 1; i++)
            {
                strDes += btys[i];
            }
            return strDes;
        }

        public static string GenerateId()
        {
            return MD52INT(Guid.NewGuid().ToString()).ToString();
        }

        public static int MD52INT(string MDKEY)
        {
            int TOTAL = 0;
            for (int i = 0; i < MDKEY.Length - 1; i++)
            {
                TOTAL += CHAR2INT(MDKEY.Substring(i, 1));
            }
            return TOTAL;
        }

        private static int CHAR2INT(string MYCHAR)
        {
            int NUM = 100;
            switch (MYCHAR)
            {
                case "A":
                    NUM = 19902;
                    break;
                case "B":
                    NUM = 15604;
                    break;
                case "C":
                    NUM = 17505;
                    break;
                case "D":
                    NUM = 15562;
                    break;
                case "E":
                    NUM = 18752;
                    break;
                case "F":
                    NUM = 1765712;
                    break;
                case "0":
                    NUM = 155675;
                    break;
                case "1":
                    NUM = 26767;
                    break;
                case "2":
                    NUM = 2567562;
                    break;
                case "3":
                    NUM = 15675692;
                    break;
                case "4":
                    NUM = 2567532;
                    break;
                case "5":
                    NUM = 1575682;
                    break;
                case "6":
                    NUM = 535392;
                    break;
                case "7":
                    NUM = 15354346;
                    break;
                case "8":
                    NUM = 1723427;
                    break;
                case "9":
                    NUM = 1342399;
                    break;
            }
            return NUM;
        }

        public static List<string> BuildListKeyword(string keyword)
        {
            var result = new List<string>();
            var words = keyword.Split(new char[] { '%', ' ' }).ToList();

            var tempKeyword = string.Join(" and ", words.ToArray());
            var lastKeyword = string.Join(" or ", words.ToArray());
            result.Add(tempKeyword);

            while (words.Count > 1)
            {
                words.RemoveAt(words.Count - 1);
                tempKeyword = string.Join(" and ", words.ToArray());
                result.Add(tempKeyword);
            }

            result.Add(lastKeyword);

            return result;
        }

        public static string StripDiacritics(string accented, string replaceby)
        {
            if (string.IsNullOrEmpty(accented)) return string.Empty;
            string strRtn;
            var regex = new Regex("\\p{IsCombiningDiacriticalMarks}+");
            string strFormD = accented.Normalize(NormalizationForm.FormD);
            strRtn = regex.Replace(strFormD, String.Empty).Replace('\u0111', 'd').Replace('\u0110', 'D');
            strRtn = Regex.Replace(strRtn, "[^a-zA-Z0-9]", replaceby);
            string dup = replaceby + replaceby;//neu co 2 ki tu thay the trung nhau thi chi nhan mot cai
            if (string.IsNullOrEmpty(dup)) return strRtn;
            while (strRtn.Contains(dup))
            {
                strRtn = strRtn.Replace(dup, replaceby);
            }
            return strRtn.Trim();
        }

        /// <summary>
        /// Sinh ra so string la chuoi cac so
        /// </summary>
        /// <param name="Length">length</param>
        /// <returns>string</returns>
        public static string GenerateRandomDigitCode(int Length)
        {
            var random = new Random();
            string s = "";
            for (int i = 0; i < Length; i++)
                s = String.Concat(s, random.Next(10).ToString());
            return s;
        }

        /// <summary>
        /// Get Current Url
        /// </summary>
        /// <returns></returns>
        public static string GetUrlOriginal()
        {

            var url = string.Format("{0}://{1}{2}{3}",
                                    HttpContext.Current.Request.Url.Scheme,
                                    HttpContext.Current.Request.Url.Host,
                                    HttpContext.Current.Request.Url.Port == 80
                                        ? string.Empty : ":" + HttpContext.Current.Request.Url.Port,
                                    HttpContext.Current.Request.ApplicationPath);
            return url;

        }


        /// <summary>
        ///     Sinh ra mang int chua dung 5 phan tu lien tiep phuc vu cho pading kieu moi
        /// </summary>
        /// <param name="currentPage"></param>
        /// <param name="totalPages"></param>
        /// <param name="itemPerPage"></param>
        /// <returns></returns>
        public static int[] GenerateArrIntForPaging(int currentPage, int totalPages, int itemPerPage)
        {
            var arr = new int[itemPerPage];
            if ((currentPage <= 5) & (totalPages <= 5))
            {
                arr = new int[totalPages];
                for (var i = 0; i < totalPages; i++)
                {
                    arr[i] = i + 1;
                }
                return arr;
            }

            if ((currentPage <= 3) & (totalPages > 5))
            {
                for (var i = 0; i < itemPerPage; i++)
                {
                    arr[i] = i + 1;
                }
                return arr;
            }

            if ((currentPage >= 4) & (totalPages > 5))
            {
                arr[0] = currentPage - 2;
                arr[1] = currentPage - 1;
                arr[2] = currentPage;
                arr[3] = currentPage + 1;
                arr[4] = currentPage + 2;
            }

            // 2 so cuoi
            if (currentPage == (totalPages - 1))
            {
                arr[0] = currentPage - 3;
                arr[1] = currentPage - 2;
                arr[2] = currentPage - 1;
                arr[3] = currentPage;
                arr[4] = currentPage + 1;
            }

            if (currentPage == totalPages)
            {
                arr[0] = currentPage - 4;
                arr[1] = currentPage - 3;
                arr[2] = currentPage - 2;
                arr[3] = currentPage - 1;
                arr[4] = currentPage;
            }

            if (currentPage > totalPages)
            {
                arr[0] = totalPages - 4;
                arr[1] = totalPages - 3;
                arr[2] = totalPages - 2;
                arr[3] = totalPages - 1;
                arr[4] = totalPages;
            }

            return arr;
        }

        /// <summary>
        /// Get menu list third level for drop down list
        /// </summary>
        /// <returns></returns>
        public static List<ProductCategoryDto> GetMenuListThreeLevel()
        {
            var result = new List<ProductCategoryDto>();
            var menuList = ProductCategoryDb.GetAll() ?? new List<ProductCategoryDto>();
            var topMenuList = (from m in menuList where m.ParentId == "0" select m).OrderBy(m=>m.Ordering);
            foreach (var item in topMenuList)
            {
                result.Add(item);
                var subMenuList = (menuList.Where(m => m.ParentId == item.Id).OrderBy(m => m.Ordering));
                foreach (var subItem in subMenuList)
                {
                    subItem.Name = "----" + subItem.Name;
                    result.Add(subItem);
                    var childMenuList = (from m in menuList where m.ParentId == subItem.Id select m).OrderBy(m => m.Ordering);
                    foreach (var childItem in childMenuList)
                    {
                        childItem.Name = "----------" + childItem.Name;
                        result.Add(childItem);
                    }
                }
            }
            result.Insert(0, new ProductCategoryDto { Id = "0", Name = "-- Danh mục sản phẩm --" });
            return result;
        }        

        /// <summary>
        /// Create product image thumbnail from xml template
        /// </summary>
        /// <param name="fullFolder"></param>
        /// <param name="fileName"></param>
        /// <param name="tempPathProductThumb"></param>
        /// <param name="imageFile"></param>
        public static void CreateProductThumbnail(string fullFolder, string fileName, string tempPathProductThumb, HttpPostedFileWrapper imageFile)
        {
            var sForThumbnail = from c in XElement.Load(HttpContext.Current.Server.MapPath(tempPathProductThumb)).Elements("size") select c;
            var sForThumbnailList = sForThumbnail.Select(xElement => xElement.FirstAttribute.Value).ToList();
            foreach (var item in sForThumbnailList)
            {
                var fullFolderThumb = Path.Combine(fullFolder, item);
                var width = int.Parse(item.Split('x')[0]);
                var height = int.Parse(item.Split('x')[1]);
                if (!Directory.Exists(fullFolderThumb))
                    Directory.CreateDirectory(fullFolderThumb);
                var imageThumbPath = Path.Combine(fullFolderThumb, fileName);
                var i = new ImageJob(imageFile, imageThumbPath, new ResizeSettings(width, height, FitMode.Pad, "jpg"));
                i.Build();
            }
        }


        /// <summary>
        /// Create product thumbnail from file
        /// </summary>
        /// <param name="fullFolderThumbnail"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="fileName"></param>
        /// <param name="tempPathProductThumb"></param>
        /// <param name="relativePathFile"></param>
        public static void CreateProductThumbnailFromFile(string fullFolderThumbnail, int width, int height, string fileName, string tempPathProductThumb, string relativePathFile)
        {
            var imageFile = new FileStream(relativePathFile, FileMode.Open, FileAccess.ReadWrite);
            var imageThumbPath = Path.Combine(fullFolderThumbnail, fileName);
            var extension = Path.GetExtension(imageThumbPath);
            if (extension != null && !extension.Equals(".db"))
            {
                var i = new ImageJob(imageFile, imageThumbPath, new ResizeSettings(width, height, FitMode.Pad, "jpg"));
                i.Build();
            }
            imageFile.Close();
        }

        /// <summary>
        /// Delete product images
        /// </summary>
        /// <param name="imagePath"></param>
        /// <param name="imageName"></param>
        public static bool DeleteProductImages(string imagePath, string imageName)
        {
            // Delete root image
            var result = false;
            try
            {
                var rootFile = HttpContext.Current.Server.MapPath(imagePath + "/" + imageName);
                if (File.Exists(rootFile))
                {
                    File.Delete(rootFile);
                }
                result = true;
            }
            catch (Exception ex)
            {
            }
            return result;
        }

   

        /// <summary>
        /// Get host name
        /// </summary>
        /// <returns></returns>
        public static string GetHostName()
        {
            var uri = HttpContext.Current.Request.Url;
            var url = uri.Scheme + Uri.SchemeDelimiter + uri.Host + (uri.Port.ToString().Equals("80") ? "" : ":" + uri.Port.ToString());
            return url;
        }

        /// <summary>
        /// Get full url
        /// </summary>
        /// <returns></returns>
        public static string GetFullUrl()
        {
            var uri = HttpContext.Current.Request.Url.AbsoluteUri;
            return uri;
        }

        /// <summary>
        /// Remove special characters
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string RemoveSpecialCharsV2(string str)
        {
            //check
            str = Regex.Replace(str, @"[^\w\.@-]", " ");
            str = Regex.Replace(str, "[.()]", " ", RegexOptions.Compiled);
            var r = new Regex(@"\s+");
            str = r.Replace(str, @" ").Trim();
            return str;
        }

        /// <summary>
        /// Lay danh sach tinh thanh quan huyen tu file Country.xml
        /// </summary>
        /// <returns></returns>
        public static List<ProvinceModel> GetProvinceList()
        {
            XDocument xmlDoc = XDocument.Load(HttpContext.Current.Server.MapPath("~/Templates/Country.xml"));

            var regions = from region in xmlDoc.Descendants("Rows")
                          where int.Parse(region.Element("ParentID").Value) == 0
                          select new
                          {
                              TinhThanhID = region.Element("TinhThanhID").Value,
                              Name = region.Element("Name").Value,
                              ParentID = region.Element("ParentID").Value,
                          };

            var tinhThanhList = new List<ProvinceModel>();

            foreach (var region in regions)
            {
                tinhThanhList.Add(new ProvinceModel()
                {
                    ProvinceId = region.TinhThanhID,
                    ProvinceName = region.Name
                });
            }
            return tinhThanhList;
        }

        //--Doc thong tin cau hinh he thong tu file XML
        public static string returnConfig(string nodeName)
        {
            var xmldoc = XDocument.Load(HttpContext.Current.Server.MapPath("~/Areas/KMFadmin/KMFsystem.xml"));
            var elementValue = (from item in xmldoc.Descendants("KMFsystem")
                                select (string)item.Element(nodeName)).SingleOrDefault();
            return elementValue;
        }
        /// <summary>
        /// Lay danh sach quan huyen tu file Country.xml
        /// </summary>
        /// <returns></returns>
        public static List<DistrictModel> GetDistrictList(int tinhThanhId)
        {
            XDocument xmlDoc = XDocument.Load(HttpContext.Current.Server.MapPath("~/Templates/Country.xml"));

            var regions = from region in xmlDoc.Descendants("Rows")
                          where int.Parse(region.Element("ParentID").Value) == tinhThanhId
                          select new
                          {
                              TinhThanhID = region.Element("TinhThanhID").Value,
                              Name = region.Element("Name").Value,
                              ParentID = region.Element("ParentID").Value,
                          };

            var quanHuyenList = new List<DistrictModel>();

            foreach (var region in regions)
            {
                quanHuyenList.Add(new DistrictModel()
                {
                    DistrictId = region.TinhThanhID,
                    DistrictName = region.Name
                });
            }
            return quanHuyenList;
        }

        public static bool SendMailRegisterSucccess(string cusName, string cusMail)
        {
            try
            {
                var mailFrom = "";
                var mailTo = cusMail;
                var mailCC = ""; //System.Configuration.ConfigurationManager.AppSettings["CCOrderMail"] + ";" + System.Configuration.ConfigurationManager.AppSettings["ReceiveOrderMail"];

                const string subject = "Kích hoạt tài khoản mới đăng ký tại babo.vn";
                var emailContent = string.Empty;

                //reading email template
                var content = ReadMailTemplate("~/Templates/Email/RegisterMailTemplate.xml");
                emailContent = string.Format(content, cusName);
                return SmtpEmailSender.Send(mailFrom, mailTo, mailCC, subject, emailContent);
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// Read XML Template
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string ReadMailTemplate(string path)
        {
            // reading email template
            var doc = XDocument.Load(HttpContext.Current.Server.MapPath(path));
            if (doc.Root != null)
            {
                var content = doc.Root.Element("content");
                if (content == null) throw new ArgumentNullException("content");
                return content.Value;
            }
            return "";
        }       
       
        public static bool CheckUserLogin()
        {
            return false;
        }

        //public static bool CheckUserRoot()
        //{
        //    var rtn = false;
        //    var pass = HttpContext.Current.Session[SessionConfig.SessionAdminPass];
        //    if (pass != null && !string.IsNullOrEmpty(pass.ToString()))
        //    {
        //        // passSalt: 74ba93f0-ab96-4342-b726-8ed768924418
        //        if (pass.Equals("919080723BDF84A4A9D2337C4657D49EEA06EBFB"))
        //        {
        //            rtn = true; // dung la root
        //        }
        //    }
        //    return rtn;
        //}
      }
}